//
//  PYMineController.m
//  IHome
//
//  Created by zhujizheng on 2020/2/15.
//  Copyright © 2019年 com.zhujizheng. All rights reserved.
//

#import "PYMineController.h"
#import "PYMineHeadCell.h"
#import "PYMineNormalCell.h"
#import "PYMineUserInfoController.h"
#import "PYCatalogueController.h"
#import "PYMapController.h"
#import "PYLabelController.h"

static NSString *const kDocuments = @"kDocuments";
static NSString *const kBundle = @"kBundle";
static NSString *const kUpdate = @"kUpdate";
static NSString *const kMap = @"kMap";
static NSString *const kLabel = @"kLabel";

@interface PYMineController () <UITableViewDelegate, UITableViewDataSource>
/// 列表
@property (nonatomic, strong) UITableView *tbView;

@property (nonatomic, copy) NSArray *keyArr;
@property (nonatomic, copy) NSDictionary *imgDict;
@property (nonatomic, copy) NSDictionary *rowNameDict;
@property (nonatomic, copy) NSDictionary *selectorDict;

@end

@implementation PYMineController

- (NSString *)packageVersion
{
    static NSString *version = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    });
    return version;
}

- (void)initTableData
{
    NSMutableArray *keyArr = [NSMutableArray array];
    NSMutableDictionary *imgDict = [NSMutableDictionary dictionary];
    NSMutableDictionary *rowNameDict = [NSMutableDictionary dictionary];
    NSMutableDictionary *selectorDict = [NSMutableDictionary dictionary];
    
    [rowNameDict setObject:@"Documents文件" forKey:kDocuments];
    [selectorDict setObject:NSStringFromSelector(@selector(clickDocuments)) forKey:kDocuments];
    [imgDict setObject:@"folder" forKey:kDocuments];
    [rowNameDict setObject:@"Bundle文件" forKey:kBundle];
    [selectorDict setObject:NSStringFromSelector(@selector(clickBundle)) forKey:kBundle];
    [imgDict setObject:@"folder" forKey:kBundle];
    NSString *updateName = [NSString stringWithFormat:@"更新App(%@)", [self packageVersion]];
    [rowNameDict setObject:updateName forKey:kUpdate];
    [selectorDict setObject:NSStringFromSelector(@selector(clickUpdate)) forKey:kUpdate];
    [imgDict setObject:@"setting" forKey:kUpdate];
    [rowNameDict setObject:@"MKMapView" forKey:kMap];
    [selectorDict setObject:NSStringFromSelector(@selector(clickMap)) forKey:kMap];
    [imgDict setObject:@"function" forKey:kMap];
    [rowNameDict setObject:@"YYLabel" forKey:kLabel];
    [selectorDict setObject:NSStringFromSelector(@selector(clickLabel)) forKey:kLabel];
    [imgDict setObject:@"function" forKey:kLabel];
    {
        NSMutableArray *keys = [NSMutableArray array];
        // Documents
        [keys addObject:kDocuments];
        // Bundle
        [keys addObject:kBundle];
        [keyArr addObject:keys];
    }
    {
        NSMutableArray *keys = [NSMutableArray array];
        // 地图
        [keys addObject:kMap];
        // YYLabel
        [keys addObject:kLabel];
        [keyArr addObject:keys];
    }
    {
        NSMutableArray *keys = [NSMutableArray array];
        // 更新App
        [keys addObject:kUpdate];
        [keyArr addObject:keys];
    }
    self.keyArr = keyArr;
    self.imgDict = imgDict;
    self.rowNameDict = rowNameDict;
    self.selectorDict = selectorDict;
    NSLog(@"self.keyArr = %@", self.keyArr);
    NSLog(@"self.imgDict = %@", self.imgDict);
    NSLog(@"self.rowNameDict = %@", self.rowNameDict);
    NSLog(@"self.selectorDict = %@", self.selectorDict);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initTableData];
    [self initTbView];
    // 遮住tbView顶部的线
    [self adjustTopWhiteViewHeight:0];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}

- (void)refreshRedPoint
{
    [self.tbView reloadData];
}

#pragma mark - tbView
- (UITableView *)tbView
{
    if (!_tbView) {
        _tbView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
        _tbView.delegate = self;
        _tbView.dataSource = self;
        _tbView.separatorInset = UIEdgeInsetsMake(0, 55, 0, 0);
        [_tbView makeDefaultStyle];
    }
    return _tbView;
}

- (void)initTbView
{
    [self.view addSubview:self.tbView];
    [self.tbView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1 + self.keyArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || section == self.keyArr.count + 1) {
        return 1;
    }
    return [[self.keyArr objectAtSafeIndex:section - 1] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        PYMineHeadCell *cell = [PYMineHeadCell cellWithTableView:tableView];
        return cell;
    } else {
        PYMineNormalCell *cell = [PYMineNormalCell cellWithTableView:tableView];
        NSString *key = [[self.keyArr objectAtSafeIndex:indexPath.section - 1] objectAtSafeIndex:indexPath.row];
        cell.title = [self.rowNameDict objectForKey:key];
        cell.icon = [UIImage imageNamed:[self.imgDict objectForKey:key]];
        return cell;
    }
    
    return [PYDefaultCell defaultCell];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 130;
    }
    return 55;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 8;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self adjustTopWhiteViewHeight:-scrollView.contentOffset.y];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        // 用户信息
        PYMineUserInfoController *userInfoC = [PYMineUserInfoController new];
        [self.navigationController pushViewController:userInfoC animated:YES];
    } else {
        NSString *key = [[self.keyArr objectAtSafeIndex:indexPath.section - 1] objectAtSafeIndex:indexPath.row];
        SEL selector = NSSelectorFromString([self.selectorDict objectForKey:key]);
        SuppressPerformSelectorLeakWarning({
            [self performSelector:selector];
        })
    }
}

- (void)clickDocuments
{
    PYCatalogueController *controller = [PYCatalogueController controllerWithFullPath:NSHomeDirectory()];
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)clickBundle
{
    PYCatalogueController *controller = [PYCatalogueController controllerWithFullPath:[[NSBundle mainBundle] bundlePath]];
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)clickUpdate
{
    NSString *url = @"https://www.pgyer.com/apiv2/app/builds";
    NSString *apiKey = @"7a9dd062078f9a189052c244927d8462";
    NSString *appKey = @"c7cee421a547a4dfb5218eda3b3f4d36";
    NSDictionary *param = @{@"appKey":appKey, @"_api_key":apiKey};
    [PYHttp requestWithURLString:url parameters:param requestType:PY_POST bodyType:PY_Form_Data success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        if (![responseObject isKindOfClass:[NSDictionary class]]) {
            return ;
        }
        NSDictionary *data = [responseObject objectForKey:@"data"];
        if (![data isKindOfClass:[NSDictionary class]]) {
            return ;
        }
        NSArray *list = [data objectForKey:@"list"];
        if (![list isKindOfClass:[NSArray class]]) {
            return;
        }
        NSDictionary *dict = [list firstObject];
        if (![dict isKindOfClass:[NSDictionary class]]) {
            return;
        }
        NSString *buildKey = [dict stringValueForKey:@"buildKey" default:nil];
        if (buildKey) {
            NSString *appDownloadUrl = [NSString stringWithFormat:@"itms-services://?action=download-manifest&url=https://www.pgyer.com/app/plist/%@", buildKey];
            NSLog(@"appDownloadUrl = %@", appDownloadUrl);
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appDownloadUrl] options:@{} completionHandler:nil];
            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appDownloadUrl]];
            }
        }
    } failure:nil];
}

- (void)clickMap
{
    PYMapController *controller = [PYMapController new];
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)clickLabel
{
    PYLabelController *controller = [PYLabelController new];
    [self.navigationController pushViewController:controller animated:YES];
}

@end
